package cn.ht.jywrwater.module.ht.service.village;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.ht.jywrwater.module.ht.controller.admin.village.vo.*;
import cn.ht.jywrwater.module.ht.dal.dataobject.village.VillageDO;
import cn.ht.jywrwater.framework.common.pojo.PageResult;

import cn.ht.jywrwater.module.ht.convert.village.VillageConvert;
import cn.ht.jywrwater.module.ht.dal.mysql.village.VillageMapper;

import static cn.ht.jywrwater.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ht.jywrwater.module.ht.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 村庄 Service 实现类
 *
 * @author hzx
 */
@Service
@Validated
public class VillageServiceImpl implements VillageService {

    @Resource
    private VillageMapper villageMapper;

    @Override
    public Long createVillage(VillageCreateReqVO createReqVO) {
        // 插入
        VillageDO village = VillageConvert.INSTANCE.convert(createReqVO);
        villageMapper.insert(village);
        // 返回
        return village.getId();
    }

    @Override
    public void updateVillage(VillageUpdateReqVO updateReqVO) {
        // 校验存在
        validateVillageExists(updateReqVO.getId());
        // 更新
        VillageDO updateObj = VillageConvert.INSTANCE.convert(updateReqVO);
        villageMapper.updateById(updateObj);
    }

    @Override
    public void deleteVillage(Long id) {
        // 校验存在
        validateVillageExists(id);
        // 删除
        villageMapper.deleteById(id);
    }

    private void validateVillageExists(Long id) {
        if (villageMapper.selectById(id) == null) {
            throw exception(VILLAGE_NOT_EXISTS);
        }
    }

    @Override
    public VillageDO getVillage(Long id) {
        return villageMapper.selectById(id);
    }

    @Override
    public List<VillageDO> getVillageList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return villageMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<VillageDO> getVillagePage(VillagePageReqVO pageReqVO) {
        return villageMapper.selectPage(pageReqVO);
    }

    @Override
    public List<VillageDO> getVillageList(VillageExportReqVO exportReqVO) {
        return villageMapper.selectList(exportReqVO);
    }

}
